package com.lagou.niancheng.lagou.service.mail.service;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service
public class MailServiceImpl implements MailService {

    @Value("${lagou.service.email.host.name}")
    private String emailHostName;

    @Value("${lagou.service.email.host.port}")
    private int emailHostPort;

    @Value("${lagou.service.email.host.fromEmail}")
    private String fromEmail;

    @Value("${lagou.service.email.host.authCode}")
    private String authCode;


    @Override
    public void sendMail(String email, String code) {
        try {
            doSendMail(email, code);
        } catch (EmailException e) {
            throw new RuntimeException(e);
        }
    }

    private void doSendMail(String toEmail, String code) throws EmailException {
        Email email = new SimpleEmail();
        email.setHostName(emailHostName);
        email.setSmtpPort(emailHostPort);
        email.setAuthenticator(new DefaultAuthenticator(fromEmail, authCode));
        email.setSSLOnConnect(true);
        email.setFrom(fromEmail);
        email.setSubject("发送验证码");
        email.setMsg("注册验证码为:" + code);
        email.addTo(toEmail);
        email.send();
    }
}
